package com.hunnyovo.springframework.beans.factory.support;

import com.hunnyovo.springframework.beans.BeansException;
import com.hunnyovo.springframework.beans.factory.config.BeanDefinition;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

/**
 * 简易实例化bean策略接口实现(JDK)
 *
 * @author Create By Cb
 * @date 2022/10/26 18:36
 **/
public class SimpleInstantiationStrategy implements InstantiationStrategy {

    @Override
    public Object instantiation(BeanDefinition beanDefinition, String beanName, Constructor<?> constructor, Object... args) throws BeansException {
        Class<?> clazz = beanDefinition.getBeanClass();
        try {
            if (constructor == null) {
                return clazz.getDeclaredConstructor().newInstance();
            } else {
                return clazz.getDeclaredConstructor(constructor.getParameterTypes()).newInstance(args);
            }
        } catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            throw new BeansException("Instantiation Bean:[" + clazz.getSimpleName() + "] Error.", e);
        }
    }

}
